import React from 'react';
import Taro from '@tarojs/taro';

import { connect } from 'react-redux';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import OrderItem from './components/OrderItem';//订单item

import ReceivingCodeInput from '@/pages/common/receiving-code-input/receiving-code';
import { Text, View, Image, Video, Button, ScrollView } from '@tarojs/components';
import ChooseImageView from '@/pages/common/image-video-upload/choose-view';
import './index.less';
import close from '../lifeOrders/img/close.png'
import { AtActionSheet, AtTextarea, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui';
import moment from 'dayjs';
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/action-sheet.scss";
import "taro-ui/dist/style/components/modal.scss";
import checkIcon from '@/assets/image/community/c_check.png';
import checkedIcon from '@/assets/image/community/c_checked.png';

const flowStatus = (status) => {
  if (status == 0) {
    return '临时有事，我不想取了';
  } else if (status == 1) {
    return '等待太久无人接单';
  } else if (status == 2) {
    return '订单信息填写有误';
  }
};


actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class OrderDetailD extends React.Component<Partial<T.IProps>, any> {

  // 使用state值
  constructor(props) {
    super(props)
    this.state = {
      payModel: false,
      cancelModel: false,
      confirmModel: false,
      paySelected: 0,
      cancelSelected: 0,
      list: [
        {
          label: '临时有事，我不想取了',
        }, {
          label: '等待太久无人接单',
        }, {
          label: '订单信息填写有误',
        }, {
          label: '其他',
        },
      ],
      value: '',
      receivingCode: '',
    }
  }

  componentDidShow() {
    this.props.actions.init()
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async checkClick(type, key) {
    let { list } = this.state;
    list.map((item, index) => {
      item.check = false;
      if (key === index) {
        item.check = true
      }
    });
    this.setState({ list: list });
  }

  async copyValue(data: string) {
    try {
      if (data === '暂无') return;
      if (!data || data.length <= 0) return;
      await Taro.setClipboardData({
        data,
      });
    } catch (error) {
      // Taro.showToast({
      //   icon: 'error',
      //   title: JSON.stringify(error),
      // });
    }
  }

  onFileChange = (files) => {
    let {
      main: { isLoading, detail, harvestCode },
      actions: { action }
    } = this.props
    if (files.length > 0) {
      detail.serviceCertificate = files[0].url
      action.commonChange('main.detail', detail)
      action.updateEscortsnatchorder()
    }
  };

  onImageClick = (item, urls) => {
    this.previewImage(item, urls);
  };
  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };


  render() {
    let { id, orderType } = Taro.getCurrentInstance()?.router?.params;
    let { paySelected, payModel, cancelModel, list, value, cancelSelected, confirmModel } = this.state;
    if (!this.props.main) return null
    let {
      main: { isLoading, detail, harvestCode, accountBalanceTotal, cancellationOptions, cancellationReason },
      actions: { action }
    } = this.props
    const imgReg = /^https?:\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i;
    const videoReg = /^https?:\/\/(.+\/)+.+(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i;

    return (
      <View className="pageOrderDetailD">
        <View className='top'>
          {
            orderType == 1 &&
            <View className='top-box'>
              {
                // detail.escortTradeStatus == 0 ?//待支付
                //   <>
                //     <View className='status'>待支付</View>
                //     <Text className='time-name'>请在<Text className='time'>14:59</Text>内完成支付，超时将自动取消订单</Text>
                //   </> :
                detail.escortTradeStatus == 0 ?//待接单
                  <>
                    <View className='status'>待接单</View>
                  </> :
                  detail.escortTradeStatus == 1 ?//服务中
                    <>
                      <View className='status'>服务中</View>
                      <Text className='time-name'>服务人员正在为您服务</Text>
                    </> :
                    detail.escortTradeStatus == 2 ?//已完成
                      <>
                        <View className='status'>已完成</View>
                        <Text className='time-name'>服务已完成</Text>
                      </> : detail.escortTradeStatus == 3 ?//已取消
                        <>
                          <View className='status'>已取消</View>
                          <Text className='time-name'>取消原因：{detail.cancellationOptions != 3 && detail.cancellationOptions != 4 ? flowStatus(detail.cancellationOptions) : (detail.cancellationReason || '其他')}</Text>
                        </> : <></>
              }
            </View>
          }
          {
            orderType == 2 &&
            <View className='top-box'>
              {
                detail.escortSnatchOrderStatus == 0 ?
                  <>
                    <View className='status'>服务中</View>
                    <Text className='time-name'>服务人员正在为您服务</Text>
                  </> :
                  detail.escortSnatchOrderStatus == 1 ?
                    <>
                      <View className='status'>已完成</View>
                      <Text className='time-name'>服务已完成</Text>
                    </> :
                    <>
                      <View className='status'>已取消</View>
                      <Text className='time-name'>已取消</Text>
                    </>
              }
            </View>
          }
        </View>
        <ScrollView scrollY className="scroll">
          {
            orderType == 1 && (detail.escortTradeStatus == 1 || detail.escortTradeStatus == 2) && //服务中、已完成
            <View className='code-box'>
              <View className="code">
                收货码： {detail.harvestCode}
              </View>
              <View className="desc">
                服务者送达时，需提供收货码，确保安全签收
              </View>
            </View>
          }

          {
            detail.escortSnatchOrderStatus == 0 && orderType == 2 &&
            <View className='upload-box'>
              <View className='upload-row'>
                <Text className='upload-f32'>上传凭证</Text>
                <Text className='upload-f28'>发生争议时，可作为判断依据</Text>
              </View>
              {
                detail.serviceCertificate ?
                  <ChooseImageView files={[{ url: detail.serviceCertificate }]} maxCount="1" onFileChange={this.onFileChange.bind(this)} /> :
                  <ChooseImageView files={[]} maxCount="1" onFileChange={this.onFileChange.bind(this)} />
              }
            </View>
          }

          {/* 两个服务中和已完成状态展示凭证 */}
          {
            (detail.escortSnatchOrderStatus == 1 && orderType == 1) || (detail.escortTradeStatus == 2 && (orderType == 2 || orderType == 1)) &&
            <View className='upload-box'>
              <View className='upload-row'>
                <Text className='upload-f32'>凭证</Text>
              </View>
              <View className='img-box'>

                {!!detail.serviceCertificate && (
                  <>
                    {imgReg.test(detail.serviceCertificate) ?//图片
                      <Image
                        onClick={(e) => {
                          e.stopPropagation()
                          this.onImageClick(detail.serviceCertificate, [detail.serviceCertificate])
                        }}
                        src={detail.serviceCertificate}
                        mode="aspectFill"
                        className="goodIcon"
                      /> :
                      <Video
                        className="goodIcon"
                        src={detail.serviceCertificate}
                        initialTime={0}
                        controls={true}
                        autoplay={false}
                        loop={false}
                        muted={false}
                      />
                    }
                  </>
                )}
              </View>
            </View>
          }

          <OrderItem order={detail} orderType={orderType} />

          <View className='order-box'>
            <View className='order-title'>订单信息</View>
            <View className='order-row'>
              <View className='left'>订单编号</View>
              {
                orderType == 1 ?
                  <View className='right'>
                    <View className='order'>{detail.id}</View>
                    <View style={{ margin: '0 10px' }}>|</View>
                    <Button onClick={(e) => this.copyValue(detail.id)} className='copy'>
                      复制
                    </Button>
                  </View> :
                  <View className='right'>
                    <View className='order'>{detail.escortTradeId}</View>
                    <View style={{ margin: '0 10px' }}>|</View>
                    <Button onClick={(e) => this.copyValue(detail.escortTradeId)} className='copy'>
                      复制
                    </Button>
                  </View>
              }
            </View>
            {
              detail.createTime &&
              <View className='order-row'>
                <View className='left'>下单时间</View>
                <View className='right'>
                  <View className='order'>{moment(detail.createTime).format('YYYY-MM-DD HH:mm:ss')}</View>
                </View>
              </View>
            }

            {
              detail.receivingTime &&
              <View className='order-row'>
                <View className='left'>接单时间</View>
                <View className='right'>
                  <View className='order'>{moment(detail.receivingTime).format('YYYY-MM-DD HH:mm:ss')}</View>
                </View>
              </View>
            }

            {
              detail.completionTime &&
              <View className='order-row'>
                <View className='left'>完成时间</View>
                <View className='right'>
                  <View className='order'>{moment(detail.completionTime).format('YYYY-MM-DD HH:mm:ss')}</View>
                </View>
              </View>
            }

            {
              detail.cancelTime &&
              <View className='order-row'>
                <View className='left'>取消时间</View>
                <View className='right'>
                  <View className='order'>{moment(detail.cancelTime).format('YYYY-MM-DD HH:mm:ss')}</View>
                </View>
              </View>
            }
          </View>

          <View className='price-box'>
            <View className='price-row'>
              <View className='price-title'>订单配送收入</View>
              <View style={{ flexDirection: 'row', alignItems: 'flex-end' }}>
                <Text className='label'>配送费 </Text>
                {/* <Text style={{ fontSize: 12, color: '#FE3831', fontWeight: 'bold' }}>¥</Text>
                <Text className="price">{detail.price}</Text> */}
                <Text className="price" style={{ marginLeft: '10rpx' }}>{detail.points}</Text>
                <Text style={{ fontSize: 14, color: '#FE3831', fontWeight: 'bold', marginLeft: '10rpx' }}>积分</Text>
              </View>
            </View>
            <View className='price-row'>
              <View className='left'>基础服务费</View>
              {/* <Text className='right'><Text style={{ fontSize: 14, fontWeight: 'bold', color: '#999999' }}>¥</Text>{detail.basePrice}</Text> */}
              <Text className='right'>{detail.basePrice}<Text style={{ fontSize: 14, fontWeight: 'bold', color: '#999999', marginLeft: '10rpx' }}>积分</Text></Text>
            </View>
            <View className='price-row'>
              <View className='left'>时段加价</View>
              {/* <Text className='right'><Text style={{ fontSize: 14, fontWeight: 'bold', color: '#999999' }}>¥</Text>{detail.timeRaise}</Text> */}
              <Text className='right'>{detail.timeRaise}<Text style={{ fontSize: 14, fontWeight: 'bold', color: '#999999', marginLeft: '10rpx' }}>积分</Text></Text>
            </View>
          </View>
          <View style={{ height: '36vh' }}></View>
        </ScrollView>
        <View className="bottom">
          <View className='btn-box'>
            {
              orderType == 1 ?
                <>
                  {
                    // (detail.escortTradeStatus == 0 || detail.escortTradeStatus == 1) &&
                    detail.escortTradeStatus == 0 &&
                    <View
                      className='btn'
                      onClick={(e) => {
                        e.stopPropagation();
                        this.setState({
                          cancelModel: true
                        })
                      }}>取消订单</View>
                  }
                  {/* {
                    detail.escortTradeStatus == 0 &&
                    <View
                      className='btn-a'
                      onClick={(e) => {
                        e.stopPropagation();
                        this.setState({
                          payModel: true
                        })
                      }}>去支付</View>
                  } */}
                  {
                    // detail.escortTradeStatus == 3 &&
                    (detail.escortTradeStatus == 2 || detail.escortTradeStatus == 3) &&
                    <View
                      className='btn'
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.showModal({
                          content: '确认删除此订单?',
                          success: function (res) {
                            if (res.confirm) {
                              action.delEscorttradeDetail(detail.id)
                            } else if (res.cancel) {
                              console.log('用户点击取消');
                            }
                          },
                          confirmColor: '#218CFF'
                        });
                      }}>删除订单</View>
                  }
                  {
                    // (detail.escortTradeStatus == 2 || detail.escortTradeStatus == 3) &&
                    (detail.escortTradeStatus == 1 || detail.escortTradeStatus == 2) &&
                    <View
                      className='btn'
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.makePhoneCall({ phoneNumber: detail.serviceCustomerAccount })
                      }}>联系TA</View>
                  }
                  {
                    // detail.escortTradeStatus == 3 &&
                    (detail.escortTradeStatus == 2 || detail.escortTradeStatus == 3) &&
                    <View
                      className='btn-a'
                      onClick={(e) => {
                        e.stopPropagation
                        Taro.navigateTo({
                          url: `/pages/package-D/addPickupCourier/index?id=${detail?.id}&deliveryAddressId=${detail?.deliveryAddressId}`,
                        });
                      }}
                    >再来一单</View>
                  }
                </> :
                <>
                  {detail.escortSnatchOrderStatus == 0 ?//服务中
                    <>
                      <View
                        className='btn-a'
                        onClick={(e) => {
                          e.stopPropagation();
                          action.commonChange('main.harvestCode', '')
                          this.setState({
                            confirmModel: true,
                          })

                        }}>确认完成</View>
                    </> :
                    <>
                      <View
                        className='btn'
                        onClick={(e) => {
                          e.stopPropagation();
                          Taro.showModal({
                            content: '确认删除此订单?',
                            success: function (res) {
                              if (res.confirm) {
                                action.delEscortsnatchorderDetail(detail.id)
                              } else if (res.cancel) {
                                console.log('用户点击取消');
                              }
                            },
                            confirmColor: '#218CFF'
                          });
                        }}>删除订单</View>
                      <View
                        className='btn-a'
                        onClick={(e) => {
                          e.stopPropagation();
                          Taro.navigateTo({
                            url: '/pages/package-D/pickupExpressDelivery/index',
                          })
                        }}>去接单</View>
                    </>
                  }
                </>
            }
          </View>
        </View>

        {/* 请选择支付方式 */}
        <AtActionSheet
          isOpened={payModel}
          onClose={() => this.setState({ payModel: false })}
          onCancel={() => this.setState({ payModel: false })}
        >
          <View className='payModel'>
            <View className='row-box'>
              <Text className='title'>请选择支付方式</Text>
              <Image className="close" src={close} mode="widthFix" onClick={(e) => { this.setState({ payModel: false }) }} />
            </View>
            <View className='model-price'>
              <Text style={{ fontSize: 14, color: '#333333', fontWeight: 'bold' }}>¥</Text>
              <Text className="price">{detail.price}</Text>
            </View>
            <Text className='integral-label'>积分已抵扣2.30元</Text>
            <View className='btn-list'>
              <View className={paySelected === 0 ? 'itemBox-a' : 'itemBox'} style={{ marginRight: '10px' }} onClick={(e) => { this.setState({ paySelected: 0 }) }} >
                <View className={paySelected === 0 ? 'item-a' : 'item'}>
                  微信支付
                </View>
              </View>
              <View className={paySelected === 1 ? 'itemBox-a' : 'itemBox'} style={{ marginLeft: '10px' }} onClick={(e) => { this.setState({ paySelected: 1 }) }} >
                <View className={paySelected === 1 ? 'item-a' : 'item'}>
                  钱包支付
                </View>
                <View className={paySelected === 1 ? 'balance-a' : 'balance'}>
                  可用余额 ¥{accountBalanceTotal}
                </View>
              </View>
            </View>
            <View className='bottomBtn'>
              付款 ¥{detail.price}
            </View>
          </View>
        </AtActionSheet>

        {/* 请选择取消原因 */}
        <AtActionSheet
          isOpened={cancelModel}
          onClose={() => this.setState({ cancelModel: false })}
          onCancel={() => this.setState({ cancelModel: false })}
        >
          <View className='cancelModel'>
            <View className='row-box'>
              <Text className='title'>请选择取消原因</Text>
              <Image className="close" src={close} mode="widthFix" onClick={(e) => { this.setState({ cancelModel: false }) }} />
            </View>
            <View className='list-box'>
              {list.map((item, index) => {
                return (
                  <View
                    className='row'
                    key={index}
                    onClick={(e) => {
                      action.commonChange('main.cancellationReason', '')
                      action.commonChange('main.cancellationOptions', index)
                    }} >
                    <Text className='label'>{item.label}</Text>
                    <Image
                      className="check"
                      src={cancellationOptions == index ? checkedIcon : checkIcon}
                      mode="widthFix" />
                  </View>
                );
              })}
              {
                cancellationOptions == 3 &&
                <AtTextarea
                  className='textarea'
                  value={cancellationReason}
                  onChange={(e) => {
                    action.commonChange('main.cancellationReason', e?.substring?.(0, 300))
                  }}
                  maxLength={300}
                  placeholder='请输入取消原因(选填)'
                  placeholderStyle={"color:#BFBFBF;font-size:14px"}
                />
              }
            </View>
            <View
              className='bottomBtn'
              onClick={(e) => {
                action.cancelEscorttrade()
                this.setState({ cancelModel: false })
              }}>
              确认取消
            </View>
          </View>
        </AtActionSheet>

        {/* 确认完成 */}
        <AtModal isOpened={confirmModel} className='confirmModel'>
          <AtModalHeader>请输入收货码</AtModalHeader>
          <AtModalContent>
            <ReceivingCodeInput
              style={{ alignItems: 'center' }}
              focus={false}
              value={harvestCode}
              toPay={(val) => {
                action.commonChange('main.harvestCode', val);
              }}
            />
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                this.setState({
                  confirmModel: false,
                })
                action.commonChange('main.harvestCode', '');
              }}>取消</Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                if (harvestCode) {
                  action.harvestCode()
                  this.setState({
                    confirmModel: false,
                  })
                } else {
                  Taro.showToast({
                    title: '请先输入收货码',
                    icon: 'none',
                    duration: 2000,
                  });
                }
              }}>确定</Button>
          </AtModalAction>
        </AtModal>

      </View>
    );
  }
}
